import { PageEntity } from '@/entity/page.entity';
import { cloneDeep } from 'lodash-es';
import { StatusMessage } from '@/enum';
import { toRefs, ref, reactive, nextTick } from 'vue';
import { useLoading } from '@sa/hooks';
import { postAction } from '@/service/request/action';

/**
 * 基本配置
 */
interface ICrudParams {
  uris: {
    deleteBatch?: string, // 批量删除接口
    delete?: string, // 单个删除接口
    exportUrl?: string, // 导出分页接口
  },
  refreshList?: Function;
  pageInfo?: PageEntity;
}
interface ICrudModal extends Api.Common.OpPath {
  title: string;
  refreshList: Function;
  otherInitMethod?: Function;
  submitTransferData?: Function;
}


export function useCrud(
  {
    uris,
    refreshList,
  }: ICrudParams
) {
  const modalFormRef = ref();
  const childRef = ref();
  const state = reactive({
    dataList: [],
    searchParams: {} as any,
    selectedRowKeys: [] as any, // 被选中的数据主键
    selectionRows: [], // 被选中的数据行
    tableHeight: 380
  });

  /**
   * 点击新增
   */
  const clickAdd = () => {
    modalFormRef.value.openDialog({
      dataId: '',
      isView: false,
      childRef,
    });
  };

  /**
   * 点击编辑
   */
  const clickEdit = (id: string, row?: any) => {
    modalFormRef.value.openDialog({
      dataId: id,
      isView: false,
      childRef,
      rowData: cloneDeep(row)
    });
  };

  /**
   * 点击查看
   */
  const clickView = (id: string, row?: any) => {
    modalFormRef.value.openDialog({
      dataId: id,
      isView: true,
      childRef,
      rowData: cloneDeep(row)
    });
  };

  /**
   * 单个删除
   * @param id id
   */
  const clickDelete = (id: string) => {
    if (!uris.delete) {
      window.$message?.error('请设置uris.delete属性!')
      return false;
    }
    postAction(uris.delete, { id }).then(res => {
      if (!res.error) {
        window.$message?.success(StatusMessage.SUCCESS);
        refreshList && refreshList();
      }
    });
  };

  /**
   * 重置选中行
   */
  const resetSelectedRowKeys = () => {
    state.selectedRowKeys = [];
    state.selectionRows = [];
  };

  return {
    modalFormRef,
    childRef,
    ...toRefs(state),
    clickAdd,
    clickEdit,
    clickView,
    clickDelete,
    resetSelectedRowKeys,
  }
}

export function useCrudModal(
  {
    title,
    createPath,
    updatePath,
    viewPath,
    refreshList,
    otherInitMethod,
    submitTransferData
  }: ICrudModal
) {
  const { loading, startLoading, endLoading } = useLoading();
  const state = reactive({
    isShowDialog: false,
    title: '',
    ruleForm: {
      id: ''
    },
    formModalRef: {} as any,
    isView: false
  });
  const openDialog = (
    {
      dataId,
      childRef,
      rowData,
      isView
    }: {
      dataId: string,
      childRef: any,
      rowData: any,
      isView: boolean
    }
  ) => {
    state.isShowDialog = true;
    state.isView = isView;
    nextTick(() => {
      state.formModalRef = childRef.value;
      state.ruleForm.id = '';
      if (dataId) {
        state.ruleForm.id = dataId;
        state.title = (isView ? '查看' : '编辑') + title;
        if (viewPath) {
          postAction(viewPath, {
            id: dataId
          }).then(res => {
            if (!res.error) {
              setFormValue(res.data);
              otherInitMethod?.(res.data);
            }
          });
        } else {
          setFormValue(rowData);
          otherInitMethod?.(rowData);
        }
      } else {
        state.title = '新增' + title;
        otherInitMethod?.();
      }
    });
  }

  const setFormValue = (formData: any) => {
    for (const o in formData) {
      if (state.formModalRef.state.ruleForm.hasOwnProperty(o)) {
        state.formModalRef.state.ruleForm[o] = formData[o];
      }
    }
    if (state.isView) {
      state.formModalRef.state.ruleForm.isView = true;
    }
  }

  const closeDialog = () => {
    state.isShowDialog = false;
  };

  const clickConfirm = () => {
    state.formModalRef.formRef.validate((err: []) => {
      if (!err) {
        let formData = {
          ...state.formModalRef.state.ruleForm,
          ...state.ruleForm
        };
        if (submitTransferData) {
          formData = submitTransferData(formData);
        }
        startLoading();
        // @ts-ignore
        postAction(state.ruleForm.id ? updatePath : createPath, formData).then(res => {
          endLoading();
          if (!res.error) {
            window.$message?.success(StatusMessage.SUCCESS);
            closeDialog();
            refreshList();
          }
        });
      }
    });
  };

  return {
    ...toRefs(state),
    openDialog,
    closeDialog,
    clickConfirm,
    loading,
  }

}
